﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TagPropagator.Data;

namespace TagPropagator
{
    public class BFSAgent : IPropagationAgent
    {
        /// <summary>
        /// Some serious refactor needed
        /// </summary>
        /// <param name="graph"></param>
        /// <param name="iterations"></param>
        public void Propagate(Graph graph, int iterations)
        {
            bool[] visited = new bool[graph.Nodes.Count];

            Queue<Node> queue = new Queue<Node>();
            Random rand = new Random();
            for (int i = 0; i < iterations; i++)
            {
                Console.WriteLine("iteracja {0}", i);
                queue.Enqueue(graph.Nodes[rand.Next(graph.Nodes.Count)]);
                while (queue.Count > 0)
                {
                    Node n = queue.Dequeue();
                    if (visited[n.ID]) continue;
                    visited[n.ID] = true;
                    foreach (var neighbour in n.Neighbours.Keys)
                    {
                        if (visited[neighbour]) continue;
                        queue.Enqueue(graph.Nodes[neighbour]);

                        foreach (var tag in n.Tags.Keys)
                        {
                            double propagationValue = Math.Log10(n.Tags[tag] + 1) * n.Neighbours[neighbour] * Constants.N;
                            if (!graph.Nodes[neighbour].Tags.ContainsKey(tag))
                                graph.Nodes[neighbour].Tags.Add(tag, propagationValue);
                            else
                            {
                                double tagWeight = graph.Nodes[neighbour].Tags[tag];
                                if (tagWeight + propagationValue > n.Tags[tag] * n.Neighbours[neighbour]) continue;
                                else graph.Nodes[neighbour].Tags[tag] += propagationValue;
                            }
                        }
                    }

                }
            }
        }
    }
}
